// HSS.Logging.Management.ConfirmPanel.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       ConfirmPanel.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/10/2010
// ----------------------------------------------------------------------------
namespace HSS.Logging.Management
{
	#region Using Directives
	using System;
	using System.ComponentModel;
	using System.Drawing;
	using System.Text;
	using System.Windows.Forms;
	using HSS.Forms;
	using System.Data.SqlClient;
	using HSS.Data;
	#endregion


	internal sealed class ConfirmPanel : WizardPanel
	{
		#region Fields
		bool done;
		BackgroundWorker worker;
		Label lblConfirm;
		Label _summary;
		private Panel pnlProgress;
		private Label lblPercentage;
		private ProgressBar progressBar1;
		TableLayoutPanel overarchingTableLayoutPanel;
		#endregion

		public ConfirmPanel()
		{
			try
			{
				this.InitializeComponent();
				base.Caption = HSS.Logging.Management.Resources.Confir_Caption;
				this.UpdateFonts();
			}
			catch { }
		}

		void Execute()
		{
			if (this.DatabaseExists(InstallWizard.ConnectionString))
			{
				InstallWizard.DatabaseExists = true;

				if (InstallWizard.Action == WizardAction.AddAllFeatures)
				{
					using (DataAccess da = new DataAccess(InstallWizard.ConnectionString))
					{
						if (SqlServices.IsInstalled(da))
						{
							MessageBox.Show("The Database is already configured on the specified server.");
							Cursor.Current = Cursors.Default;
							this.lblConfirm.Text = "The Database is already configured on the specified server.";
							this.lblConfirm.Text += Environment.NewLine;
							this.lblConfirm.Text += Environment.NewLine;
							this.lblConfirm.Text += "Click previous to change your settings.";
							this.ParentWizard.PreviousButton.Enabled = true;
							return;
						}
					}
				}
			}
			else if (InstallWizard.Action == WizardAction.RemoveAllFeatures)
			{
				MessageBox.Show("The Database does not exist on the specified server.");
				Cursor.Current = Cursors.Default;
				this.lblConfirm.Text = "The Database does not exist on the specified server.";
				this.lblConfirm.Text += Environment.NewLine;
				this.lblConfirm.Text += Environment.NewLine;
				this.lblConfirm.Text += "Click previous to change your settings.";
				this.ParentWizard.PreviousButton.Enabled = true;
				return;
			}

			this.progressBar1.Value = 0;
			this.progressBar1.Visible = true;
			this.lblPercentage.Visible = true;
			worker = new BackgroundWorker();
			worker.WorkerReportsProgress = true;
			worker.WorkerSupportsCancellation = true;
			worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
			worker.DoWork += new DoWorkEventHandler(worker_DoWork);
			worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
			worker.RunWorkerAsync();
		}

		bool DatabaseExists(string connectionString)
		{
			try
			{
				SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(connectionString);
				string destinationDb = csb.InitialCatalog;
				csb.InitialCatalog = string.Empty;
				using (DataAccess da = new DataAccess(csb.ConnectionString))
					return SqlServices.DatabaseExists(da, destinationDb);
			}
			catch
			{
				return false;
			}
		}

		private void InitializeComponent()
		{
			this.lblConfirm = new System.Windows.Forms.Label();
			this._summary = new System.Windows.Forms.Label();
			this.overarchingTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
			this.pnlProgress = new System.Windows.Forms.Panel();
			this.lblPercentage = new System.Windows.Forms.Label();
			this.progressBar1 = new System.Windows.Forms.ProgressBar();
			this.overarchingTableLayoutPanel.SuspendLayout();
			this.pnlProgress.SuspendLayout();
			this.SuspendLayout();
			// 
			// _confirmLabel
			// 
			this.lblConfirm.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.lblConfirm.Location = new System.Drawing.Point(3, 13);
			this.lblConfirm.Name = "_confirmLabel";
			this.lblConfirm.Size = new System.Drawing.Size(538, 215);
			this.lblConfirm.TabIndex = 100;
			// 
			// _summary
			// 
			this._summary.AutoSize = true;
			this._summary.Location = new System.Drawing.Point(3, 0);
			this._summary.Name = "_summary";
			this._summary.Size = new System.Drawing.Size(92, 13);
			this._summary.TabIndex = 101;
			this._summary.Text = "Settings summary:";
			// 
			// overarchingTableLayoutPanel
			// 
			this.overarchingTableLayoutPanel.AutoSize = true;
			this.overarchingTableLayoutPanel.ColumnCount = 1;
			this.overarchingTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 456F));
			this.overarchingTableLayoutPanel.Controls.Add(this._summary, 0, 0);
			this.overarchingTableLayoutPanel.Controls.Add(this.lblConfirm, 0, 1);
			this.overarchingTableLayoutPanel.Controls.Add(this.pnlProgress, 0, 2);
			this.overarchingTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
			this.overarchingTableLayoutPanel.Location = new System.Drawing.Point(0, 0);
			this.overarchingTableLayoutPanel.Name = "overarchingTableLayoutPanel";
			this.overarchingTableLayoutPanel.RowCount = 3;
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
			this.overarchingTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
			this.overarchingTableLayoutPanel.Size = new System.Drawing.Size(544, 274);
			this.overarchingTableLayoutPanel.TabIndex = 1;
			// 
			// pnlProgress
			// 
			this.pnlProgress.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.pnlProgress.Controls.Add(this.lblPercentage);
			this.pnlProgress.Controls.Add(this.progressBar1);
			this.pnlProgress.Location = new System.Drawing.Point(3, 231);
			this.pnlProgress.Name = "pnlProgress";
			this.pnlProgress.Size = new System.Drawing.Size(538, 40);
			this.pnlProgress.TabIndex = 102;
			// 
			// lblPercentage
			// 
			this.lblPercentage.Dock = System.Windows.Forms.DockStyle.Fill;
			this.lblPercentage.Location = new System.Drawing.Point(0, 23);
			this.lblPercentage.Name = "lblPercentage";
			this.lblPercentage.Size = new System.Drawing.Size(538, 17);
			this.lblPercentage.TabIndex = 0;
			this.lblPercentage.Text = "5%";
			this.lblPercentage.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.lblPercentage.Visible = false;
			// 
			// progressBar1
			// 
			this.progressBar1.Dock = System.Windows.Forms.DockStyle.Top;
			this.progressBar1.Location = new System.Drawing.Point(0, 0);
			this.progressBar1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 2);
			this.progressBar1.Name = "progressBar1";
			this.progressBar1.Size = new System.Drawing.Size(538, 23);
			this.progressBar1.TabIndex = 1;
			this.progressBar1.Visible = false;
			// 
			// ConfirmPanel
			// 
			this.Controls.Add(this.overarchingTableLayoutPanel);
			this.Name = "ConfirmPanel";
			this.overarchingTableLayoutPanel.ResumeLayout(false);
			this.overarchingTableLayoutPanel.PerformLayout();
			this.pnlProgress.ResumeLayout(false);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		protected override void OnFontChanged(EventArgs e)
		{
			base.OnFontChanged(e);
			this.UpdateFonts();
		}

		public override bool OnNext()
		{
			if (done)
			{
				this.ParentWizard.FormClosing -= new FormClosingEventHandler(ParentWizard_FormClosing);
				done = false;
				return true;
			}
			else
			{
				Cursor.Current = Cursors.WaitCursor;
				this.ParentWizard.FormClosing += new FormClosingEventHandler(ParentWizard_FormClosing);
				this.ParentWizard.PreviousButton.Enabled = false;
				this.ParentWizard.NextButton.Enabled = false;
				this.ParentWizard.FinishButton.Enabled = false;
				if (InstallWizard.Action == WizardAction.AddAllFeatures)
					this.lblConfirm.Text = "Installing... please wait.";
				else
					this.lblConfirm.Text = "Uninstalling... please wait.";
				this.Execute();
				return false;
			}
		}

		protected override void OnVisibleChanged(EventArgs e)
		{
			if (this.Visible)
			{
				InstallWizard.DatabaseExists = false;
				StringBuilder builder = new StringBuilder();
				builder.Append(string.Format(HSS.Logging.Management.Resources.Server_name, InstallWizard.Server));
				builder.Append(string.Format(HSS.Logging.Management.Resources.Database_name, InstallWizard.Database));
				builder.Append("\r\n");
				builder.Append(HSS.Logging.Management.Resources.Hit_next_button);
				this.lblConfirm.Text = builder.ToString();
				this.progressBar1.Visible = false;
				this.lblPercentage.Visible = false;
			}
		}

		void UpdateFonts()
		{
			Font font = new Font(this.Font, FontStyle.Bold);
			this._summary.Font = font;
		}
		void GoNext()
		{
			done = true;
			Cursor.Current = Cursors.Default;
			this.ParentWizard.NextButton.Enabled = true;
			this.ParentWizard.NextButton.Text = "Next";
			this.ParentWizard.NextPanel();
		}
		void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (e.Cancelled)
			{
				if (InstallWizard.Action == WizardAction.AddAllFeatures)
					InstallWizard.Error = new Exception("Install was cancelled");
				else
					InstallWizard.Error = new Exception("Uninstall was cancelled");
			}
			else if (null != e.Error)
			{
				InstallWizard.Error = e.Error;
			}
			else
			{
				InstallWizard.Error = null;
				Console.WriteLine("Completed!");
			}

			this.GoNext();
		}
		void worker_DoWork(object sender, DoWorkEventArgs e)
		{
			bool success = false;

			if (InstallWizard.Action == WizardAction.AddAllFeatures)
				success = SqlServices.Install(worker);
			else
				success = SqlServices.Uninstall(worker);

			e.Cancel = !success;
		}
		void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			var val = e.ProgressPercentage;
			if (val > this.progressBar1.Maximum)
				val = this.progressBar1.Maximum;
			this.progressBar1.Value = val;
			this.progressBar1.Update();
			this.lblPercentage.Text = string.Format("{0}: {1}%", e.UserState, val);
		}
		void ParentWizard_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.ParentWizard.FormClosing -= new FormClosingEventHandler(ParentWizard_FormClosing);
			if (null != worker && worker.IsBusy)
			{
				e.Cancel = true;
				if (worker.WorkerSupportsCancellation)
					worker.CancelAsync();
				else
					MessageBox.Show("Please wait for the application to complete.");
			}
		}
	}
}